package com.dgsrz.demo.texture;

import com.dgsrz.demo.util.Color;
import com.dgsrz.demo.util.ColorUtils;

import javax.microedition.khronos.opengles.GL10;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

/**
 * Created by dgsrz on 15/7/2.
 */
public class GradientTexture extends TextureBase {

    private final int   TEX_VERTEX_NUM = 6;
    private final float TEX_WIDTH_AA   = 0.015625f;

    private final float TEX_VERTICES[] = {
            0.0f, 0f, 0,
            0.078125f - TEX_WIDTH_AA, 0f, 0,

            0.078125f + TEX_WIDTH_AA, 0f, 0,
            0.1875f - TEX_WIDTH_AA, 0f, 0,

            0.1875f + TEX_WIDTH_AA, 0f, 0,
            1.0f, 0f, 0,
    };

    private final float TEX_COLOR_COORDS[] = {
            0, 0, 0, 0,
            0, 0, 0, 0.33f,

            1.0f, 1.0f, 1.0f, 1.0f,
            1.0f, 1.0f, 1.0f, 1.0f,

            0.0f, 0.0f, 0.8f, 0.5f,
            0.0f, 0.3f, 1.0f, 0.5f,
    };

    private FloatBuffer mVertexBuffer;
    private FloatBuffer mColorBuffer;

    public GradientTexture(final GL10 gl) {
        super(gl);

        Color innerColor = ColorUtils.makeInnerColor(Color.USER_BLUE);
        Color outerColor = ColorUtils.makeOuterColor(Color.USER_BLUE);

        TEX_COLOR_COORDS[16] = outerColor.getR() / 255f;
        TEX_COLOR_COORDS[17] = outerColor.getG() / 255f;
        TEX_COLOR_COORDS[18] = outerColor.getB() / 255f;
        TEX_COLOR_COORDS[19] = outerColor.getA() / 255f;

        TEX_COLOR_COORDS[20] = innerColor.getR() / 255f;
        TEX_COLOR_COORDS[21] = innerColor.getG() / 255f;
        TEX_COLOR_COORDS[22] = innerColor.getB() / 255f;
        TEX_COLOR_COORDS[23] = innerColor.getA() / 255f;

        ByteBuffer vertexBuffer = ByteBuffer.allocateDirect(TEX_VERTEX_NUM * 3 * 4);
        vertexBuffer.order(ByteOrder.nativeOrder());
        mVertexBuffer = vertexBuffer.asFloatBuffer();
        mVertexBuffer.put(TEX_VERTICES);
        mVertexBuffer.position(0);

        ByteBuffer colorBuffer = ByteBuffer.allocateDirect(TEX_VERTEX_NUM * 4 * 4);
        colorBuffer.order(ByteOrder.nativeOrder());
        mColorBuffer = colorBuffer.asFloatBuffer();
        mColorBuffer.put(TEX_COLOR_COORDS);
        mColorBuffer.position(0);
    }

    @Override
    public void drawTexture() {
        final GL10 gl = getGLStateManager();

        gl.glFrontFace(GL10.GL_CW);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
        gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer);
        gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, TEX_VERTEX_NUM);
    }
}
